<template>
  <div class="app-container">

    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="22" :xs="24">
        <!-- 搜索框，根据条件查询       -->
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="70px">

          <el-form-item label="所属科室" prop="suDName">
            <el-select
              v-model="queryParams.suDName"
              placeholder="请选择所属科室"
              clearable
              size="small"
              style="width: 160px"
            >
              <el-option
                v-for="dict in hisDms"
                :key="dict.sdName"
                :label="dict.sdName"
                :value="dict.sdName"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="用户名称" prop="suName">
            <el-input
              v-model="queryParams.suName"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 160px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="手机号码" prop="suPhone">
            <el-input
              v-model="queryParams.suPhone"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 160px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="用户状态"
              clearable
              size="small"
              style="width: 160px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>

          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              style="width: 300px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>

        </el-form>
        <!--  增删改查按钮    -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:user:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
            >删除</el-button>
          </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-thumb"
                size="mini"
                :disabled="multiple"
                @click="handleRole"
                v-hasPermi="['system:user:addRole']"
              >分配角色</el-button>
            </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-refresh"
              size="mini"
              :disabled="single"
              @click="handleResetPwd"
              v-hasPermi="['system:user:resetPwd']"
            >重置密码</el-button>
          </el-col>
        </el-row>
        <!-- 查出来的数据表格展示 也包含每条数据后面修改删除分配角色按钮  -->
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="用户ID" align="center" key="suId" prop="suId" />
          <el-table-column label="用户姓名" align="center" key="suName" prop="suName" :show-overflow-tooltip="true" />
          <el-table-column label="科室" align="center" key="suDName" prop="suDName"  :show-overflow-tooltip="true" />
          <el-table-column label="手机号码" align="center" key="suPhone" prop="suPhone" width="160" :show-overflow-tooltip="true" />
          <el-table-column label="性别" align="center" key="suGender" prop="suGender" :formatter="genderFormat"/>
          <el-table-column label="年龄" align="center" key="suAge"  prop="suAge"  />
          <el-table-column label="是否排班" align="center" key="suOffice"  prop="suOffice" :formatter="officeFormat"/>
          <el-table-column label="级别" align="center" key="suGrade"  prop="suGrade" />
          <el-table-column label="背景" align="center" key="suBackground"  prop="suBackground" /> >
          <el-table-column  label="状态"   align="center" key="status" prop="status"  :formatter="statusFormat" ></el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="200"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']"
              >修改</el-button>
              <el-button
                v-if="scope.row.suId !== 1"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
              >删除</el-button>
              <el-button
                v-if="scope.row.suId !== 1"
                size="mini"
                type="text"
                icon="el-icon-thumb"
                @click="handleRole(scope.row)"
                v-hasPermi="['system:user:addRole']"
              >分配角色</el-button>
            </template>
          </el-table-column>

        </el-table>
        <!--分页展示相关  -->
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="suName">
              <el-input v-model="form.suName" placeholder="请输入用户名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号" prop="suPhone">
              <el-input v-model="form.suPhone" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="所属科室" prop="suDName">
              <el-select
                v-model="form.suDName"
                placeholder="请选择所属科室"
                clearable
                size="small"
                style="width: 200px"
              >
                <el-option
                  v-for="dict in hisDms"
                  :key="dict.sdName"
                  :label="dict.sdName"
                  :value="dict.sdName"
                />
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="级别" prop="suGrade">
              <el-select
                v-model="form.suGrade"
                placeholder="用户级别"
                clearable
                size="small"
                style="width: 200px"
              >
                <el-option
                  v-for="dict in usersGrade"
                  :key="dict.suGrade"
                  :label="dict.suGrade"
                  :value="dict.suGrade"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="年龄" prop="suAge">
              <el-input-number v-model="form.suAge" placeholder="18"></el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="背景" prop="suBackground">
              <el-select
                v-model="form.suBackground"
                placeholder="学历"
                clearable
                size="small"
                style="width: 200px"
              >
                <el-option
                  v-for="dict in usersBack"
                  :key="dict.suBackground"
                  :label="dict.suBackground"
                  :value="dict.suBackground"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>

          <el-col :span="12">
            <el-form-item label="性别">
              <el-radio-group v-model="form.suGender">
                <el-radio
                  v-for="dict in sexOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="是否排班">
              <el-radio-group v-model="form.suOffice">
                <el-radio
                  v-for="dict in officeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

   <!-- 分配角色对话框-->
    <el-dialog :title="title" :visible.sync="open2" width="700px" append-to-body>
      <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange2">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="ID" align="center" key="roleId" prop="roleId" />
        <el-table-column label="角色名称" align="center" key="roleName" prop="roleName" :show-overflow-tooltip="true" />
        <el-table-column label="权限编码" align="center" key="roleKey" prop="roleKey"  :show-overflow-tooltip="true" />
        <el-table-column label="备注" align="center" key="remark" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" key="createTime" prop="createTime" width="200px" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRloeForm">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>





<script>
  // 导入，需要发请求的方法都要在这导入相应的方法所在的js文件
import { listAllhisdm, listUser, listAllusers, usersGrade,usersBack,listRole,addUser,getUser,updateUser,delUser,allotRole,resetUserPwd, } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  components: { Treeselect },

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //选中的角色ID数组
      rids:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 角色表格数据
      roleList: null,
      // 弹出层标题
      title: "",
      // 是否显示增加修改弹出层
      open: false,
      // 是否显示角色弹出层
      open2:false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 排班是否数据字典
      officeOptions: [],
       //科室数据集合
      hisDms:[],
       //用户数据集合
      users:[],
      //用户集合要级别
      usersGrade:[],
      //用户集合要背景
      usersBack:[],
      // 表单参数
      form: {},

      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        suId:undefined,
        suName: undefined,
        suPhone: undefined,
        status: undefined,
        suDName:undefined,
      },
      // 表单校验
      rules: {
          suName: [
            { required: true, message: "用户名称不能为空", trigger: "blur" }
          ],
          suGrade: [
              { required: true, message: "用户级别不能为空", trigger: "blur" }
          ],
          suBackground: [
              { required: true, message: "用户背景不能为空", trigger: "blur" }
          ],
          suDName: [
              { required: true, message: "用户所属科室不能为空", trigger: "blur" }
          ],
          suPhone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            required: true,
            trigger: "blur"
          }
        ]
      }
    };
  },

  created() { //已创建，相当于onload事件，即页面加载时就会执行的方法，而且当一个方法执行成功后，下面的方法不会执行。
    this.getAllhisdms();
    this.getAllUsers();
    this.getusersGrade();
    this.getusersBack();
    this.getList();
    this.getRole();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
     this.getDicts("sys_yes_no").then(response => {
          this.officeOptions = response.data;
     });
    this.getDicts("sys_user_sex").then(response => {
      this.sexOptions = response.data;
    });
  },
  methods: {
    /**  查询所有科室 */
      getAllhisdms(){
          listAllhisdm().then(response =>{
            this.hisDms=response.data;
          }
          );
      },
      //查询所有用户详细信息
      getAllUsers(){
          listAllusers().then(response =>{
              this.users=response.data;
          }
          );
      },
      //查询用户的级别有哪些
      getusersGrade(){
          usersGrade().then(response =>{
                  this.usersGrade=response.data;
              }
          );
      },
      //查询用户的背景有哪些
      getusersBack(){
          usersBack().then(response =>{
                  this.usersBack=response.data;
              }
          );
      },
     /** 分页查询用户列表 */
      getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
     /** 查询角色列表 */
      getRole() {
          this.loading = true;
          listRole().then(response => {
                  this.roleList = response.data;
                  this.loading = false;
              }
          );
      },

  //  对话框取消时关闭对话框。
    cancel() {
        this.open = false;
        this.reset();
    },
      //  分配角色对话框取消时，关闭对话框。
    cancel2() {
         this.open2 = false;
         this.reset2();
    },
    // 表单重置
    reset() {
      this.form = {
        suId: undefined,
        suName:undefined,
        suPhone:undefined,
        suDName:undefined,
        suGrade:undefined,
        suAge:undefined,
        suBackground:undefined,
        suGender:'男',
        status: "0",
        suOffice: "N",
      };
      this.resetForm("form");
    },
      //分配角色的rids置为空
     reset2(){
          this.rids=[];
     },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 用户多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.suId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
      // 角色多选框选中数据
      handleSelectionChange2(selection) {
          this.rids = selection.map(item => item.roleId);

      },
      // 菜单状态字典翻译1状态
      statusFormat(row, column) {
          return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 菜单状态字典翻译2是否排班
      officeFormat(row, column) {
          return this.selectDictLabel(this.officeOptions, row.suOffice);
      },
      // 菜单状态字典翻译3男女
      genderFormat(row, column) {
          return this.selectDictLabel(this.sexOptions, row.suGender);
      },
      /** 新增按钮操作 */
      handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },

//    分配角色操作
      handleRole(row){
          this.ids = row.suId|| this.ids;
          this.open2 = true;
          this.title = "分配角色";
      },
    /** 修改按钮操作 */
      handleUpdate(row) {
          this.reset();
          const suId = row.suId|| this.ids;
          getUser(suId).then(response => {
              this.form = response.data;
              this.open = true;
              this.title = "修改用户";
          });
      },

      /** 新增修改提交按钮 */
      submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.suId != undefined) {
            updateUser(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

      /** 分配角色确定按钮 */
      submitRloeForm: function() {
          allotRole(this.ids,this.rids).then(response => {
              this.msgSuccess("角色分配成功");
              this.open2 = false;
              this.getList();
              this.getRole();
          });
      },

    /** 删除按钮操作 */
    handleDelete(row) {
      const suIds = row.suId || this.ids;
      this.$confirm('是否确认删除用户ID为"' + suIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUser(suIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },

      /** 重置密码按钮操作 */
    handleResetPwd(row) {
          const suId = row.suId || this.ids;
          this.$confirm('是否确认重置用户ID为"' + suId + '"的密码?', "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          }).then(function() {
              return resetUserPwd(suId);
          }).then(() => {
              this.getList();
              this.msgSuccess("重置密码成功");
          })
      },

  }
};
</script>
